/**
 * @Author: langchenglai
 * @Date:   2018-02-05 19:45:49
 * @Email:  lclangcheng@gmail.com
 * @Filename: base_component.js
 * @Last modified by:   lclangcheng
 * @Last modified time: 2018-10-22 17:05:19
 */

'use strict'
const CustomError = require('../libs/custom_error')
const moment = require('moment')
const utils = require('../libs/utils')
const mem = require('mem')
const esClient = require('../db/elasticsearch')

class BaseService {
  /**
   * 创建错误对象
   * @param {Number} status
   * @param {String} message
   */
  static createError (status = 400, message) {
    return new CustomError(status, message)
  }

  /**
   * 格式化日期
   * @param {Object} objRawObj
   */
  static normalizeDate (objRawObj) {
    const obj = objRawObj
    if (!obj) {
      return null
    }

    for (let key of Object.keys(obj)) {
      if (moment.isDate(obj[key])) {
        obj[key] = utils.formatTime(obj[key])
      }
    }

    return obj
  }

  static async getTokens (strIndex, strAnalyzer, strKeyword) {
    const index = strIndex
    const analyzer = strAnalyzer
    const keyword = strKeyword
    const tokens = []

    if (index) {
      const analyzerOptions = {
        index: index,
        body: {
          analyzer: analyzer,
          text: keyword
        }
      }
      const resToken = await esClient.indices.analyze(analyzerOptions)
      if (resToken && resToken.tokens.length > 0) {
        for (let j = 0; j < resToken.tokens.length; j++) {
          const one = resToken.tokens[j]
          const token = one['token']
          tokens.push(token)
        }
      }
    }
    return tokens
  }
}

// BaseService.getList1 = mem(async function getMemList (options) {
//   await utils.sleep(5000)
// }, { maxAge: 10000 })

module.exports = BaseService
